package com.vegetable.modules.controller.inbound;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.poi.excel.style.StyleUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.vegetable.common.annotation.PreventDuplicateSubmit;
import com.vegetable.common.annotation.SysLog;
import com.vegetable.common.utils.ExcelUtils;
import com.vegetable.common.utils.PageUtils;
import com.vegetable.common.utils.R;
import com.vegetable.modules.controller.AbstractController;
import com.vegetable.modules.entity.baseData.AccountDetails;
import com.vegetable.modules.entity.finance.po.PackCanPayPO;
import com.vegetable.modules.entity.inbound.PackDelivery;
import com.vegetable.modules.entity.inbound.PackDeliveryTeam;
import com.vegetable.modules.entity.inbound.po.PackDeliverySequencePO;
import com.vegetable.modules.entity.inbound.vo.PackDeliverySequenceVO;
import com.vegetable.modules.entity.stock.to.StockFlowDTO;
import com.vegetable.modules.service.inbound.IPackDeliveryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 加工打包 前端控制器
 * </p>
 *
 * @author wangruijie
 * @since 2024-03-21
 */
@Slf4j
@RestController
@RequestMapping("/inStorage/packDelivery")
@AllArgsConstructor
@Api(value = "加工打包", tags = "加工打包")
public class PackDeliveryController extends AbstractController {

    private IPackDeliveryService packDeliveryService;
    /**
     * 所有加工打包列表
     */
    @GetMapping("/list")
    @ApiOperation(value = "条件查询加工打包列表", notes = "条件查询加工打包列表")
    public R list(@RequestParam Map<String, Object> params){
        log.info("条件查询加工打包列表{}", JSON.toJSONString(params));
        PageUtils page = packDeliveryService.queryPage(params);
        return R.data( page);
    }

    /**
     * 详情加工打包
     */
    @SysLog(value = "详情加工打包")
    @GetMapping("/detailPackDelivery")
    @ApiOperation(value = "根据id查询详情加工打包", notes = "根据id查询详情加工打包")
    public R detailPackDelivery(Long id){
        if (id == null || id == -1){
            return R.fail("订单主键不能为空");
        }
        log.info("根据id查询详情加工打包：{}", JSON.toJSONString(id));
        return packDeliveryService.detailPackDelivery(id);
    }

    /**
     * 新增加工打包
     */
    @SysLog(value = "分配班组")
    @PostMapping("/allocateTeams")
    @ApiOperation(value = "分配班组", notes = "分配班组")
    public R allocateTeams(@RequestBody List<PackDeliveryTeam> po) throws Exception {
        if(CollectionUtil.isEmpty(po)){
            throw new Exception("班组不能为空啊");
        }
        int res = packDeliveryService.allocateTeams(po);
        return R.data(res);
    }

    /**
     * 新增加工打包
     */
    @SysLog(value = "新增加工打包")
    @PostMapping("/savePackDelivery")
    @ApiOperation(value = "新增加工打包", notes = "新增加工打包")
    public R savePackDelivery(@RequestBody PackDelivery packDelivery) throws Exception {
        if(Objects.isNull(packDelivery.getMoney())){
            packDelivery.setMoney(BigDecimal.ZERO);
        }
        log.info("新增加工打包：{}", JSON.toJSONString(packDelivery));
        packDelivery.setCreateUserId(getUserId());
        return packDeliveryService.saveOrEdit(packDelivery);
    }

    /**
     * 修改加工打包
     */
    @SysLog(value = "修改加工打包")
    @PostMapping("/updatePackDelivery")
    @ApiOperation(value = "修改加工打包", notes = "修改加工打包")
    public R updatePackDelivery(@RequestBody PackDelivery packDelivery){
        if(Objects.isNull(packDelivery.getMoney())){
            packDelivery.setMoney(BigDecimal.ZERO);
        }
        log.info("修改加工打包：{}", JSON.toJSONString(packDelivery));
        if (packDelivery.getId() == null || packDelivery.getId() == -1){
            return R.fail("订单主键不能为空");
        }
        packDelivery.setCreateUserId(getUserId());
        try {
            return packDeliveryService.saveOrEdit(packDelivery);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("错误信息:{}",e.getLocalizedMessage());
            return R.fail(e.getMessage());
        }
    }

    /**
     * 提交加工打包
     */
    @SysLog(value = "提交加工打包")
    @PostMapping("/submitPackDelivery")
    @PreventDuplicateSubmit(expireTime = 5)
    @ApiOperation(value = "提交加工打包", notes = "提交加工打包")
    public R submitPackDelivery(@RequestBody PackDelivery packDelivery) throws Exception {
        if(Objects.isNull(packDelivery.getMoney())){
            packDelivery.setMoney(BigDecimal.ZERO);
        }
        log.info("提交加工打包：{}", JSON.toJSONString(packDelivery));
        packDelivery.setCreateUserId(getUserId());
        return packDeliveryService.submitPackDelivery(packDelivery);
    }

    /**
     * 删除加工打包
     */
    @SysLog(value = "删除加工打包")
    @GetMapping("/deletePackDelivery")
    @ApiOperation(value = "根据id删除加工打包", notes = "根据id删除加工打包")
    public R deletePackDelivery(Long id) throws Exception {
        log.info("删除加工打包：{}", JSON.toJSONString(id));
        return packDeliveryService.deletePackDelivery(id);
    }
    @SysLog(value = "最近的加工打包")
    @GetMapping("/lastOrder")
    @ApiOperation(value = "最近的加工打包", notes = "最近的加工打包")
    public R lastOrder(Long commodityId){
        log.info("最近的加工打包：{}", JSON.toJSONString(commodityId));
        return packDeliveryService.lastOrder(commodityId);
    }

    @PostMapping("/statisticsPack")
    @ApiOperation(value = "统计加工打包列表", notes = "统计库存流水列表", response = StockFlowDTO.class)
    public R statisticsPack(@RequestBody PackDeliverySequencePO po){
        IPage<PackDeliverySequenceVO> result = packDeliveryService.statisticsPackDelivery(po);
        return R.data(result);
    }

    @GetMapping("/exportTemplate")
    @ApiOperation(value = "导出加工打包统计信息", notes = "导出加工打包统计信息")
    public R exportTemplate(PackDeliverySequencePO po) throws IOException {
        po.setLimit(Integer.MAX_VALUE);
        IPage<PackDeliverySequenceVO> result = packDeliveryService.statisticsPackDelivery(po);
        List<PackDeliverySequenceVO> orderList = CollectionUtil.isEmpty(result.getRecords()) ? new ArrayList<>() : result.getRecords();
        // 生成导出excel对象
        ExportParams exportParams = new ExportParams();
        exportParams.setSheetName("加工打包");
        //开始导出
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, PackDeliverySequenceVO.class, orderList);
        workbook.createCellStyle();
        StyleUtil.createHeadCellStyle(workbook);

        String fileName = "日交接单模板" + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        ExcelUtils.downLoadExcel(fileName,workbook);
        return R.success("");
    }

    @PostMapping("/canPaymentList")
    @ApiOperation(value = "查询可收款的班组", notes = "查询可收款的班组")
    public R canPaymentList(@RequestBody PackCanPayPO po){
        log.info("查询可收款的班组{}", po);
        List<AccountDetails> list= packDeliveryService.canPaymentList(po);
        return R.data(list);
    }
}
